﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.IO;
using LikeTryHacker;
using System.Text.RegularExpressions;
using System.Configuration;
using System.ServiceModel;
using Contract;
using System.Runtime.Serialization;
using System.Xml;

namespace LikeTryCore
{
	public class LikeTry
	{
		#region Fields
		private Dictionary<string, string> TaskDictionary = new Dictionary<string, string>();
		public WaitCallback Finished { get; private set; }
        private static readonly string CheckTaskOpen = "http://www.liketry.com/task_open.php";
		private static readonly string GetTaskUrl = "http://www.liketry.com/action/task_ajax.php?action=taskcheck&main=day&sub=d{0}";
		private static readonly string ApplyTaskUrl = "http://www.liketry.com/action/task_ajax.php?action=getprice&main=day&sub=d{0} ";
        private static readonly string ApplyWeekTaskUrl = "http://www.liketry.com/action/task_ajax.php?action=taskcheck&main=week&sub=w_{0}";
		private static readonly string EmptyImageUrl = "http://images.liketry.com/images/lyl-btn.png";
		private static readonly string ApplyGoodsStep1 = "http://www.liketry.com/apply.php?product_no={0}";
        private static readonly string AccountFileLocation = ConfigurationManager.AppSettings["LogonDataLocation"];
        private static readonly string AlreadyApplyErrorMessage = ConfigurationManager.AppSettings["AlreadyApplyErrorMessage"];// "本会员已经申领过此产品" ;
        private static readonly string SchoolOnlyErrorMessage = ConfigurationManager.AppSettings["SchoolOnlyErrorMessage"];//"抱歉，您所在的楼宇非院校地址，无法申领此产品";
        private static readonly string VIPErrorMessage = ConfigurationManager.AppSettings["VIPErrorMessage"];//"VIP保护期";
        private static readonly string XiYuanNotEnough = ConfigurationManager.AppSettings["XiYuanNotEnough"];//"会员喜元数量不足或无此电子券";
        private static string FrequTime = ConfigurationManager.AppSettings["GetLastestGoodTime"];
        private static int MaxRetryTimes = Convert.ToInt32(ConfigurationManager.AppSettings["MaxRetryTimes"]);
		public  List<string> NonAvailbaleGoods = new List<string>();
		private static readonly List<GoodType> AllGoods = new List<GoodType>();

		public long CurrentXiYuan = 0;
		public long CurrentJiFen = 0;
		public string UserName { get; set; }
		private string Password { get; set; }
		public string Cookies { get; set; }

		private Dictionary<TaskItem, bool> Result;

		public bool Initilzated { get; private set; }

		public WebHelper Web { get; private set; }

        public LikeTry(string cookies, WaitCallback callBack = null)
            : this(string.Empty, string.Empty, cookies, callBack)
        {
            var lists = ConfigurationManager.AppSettings["excludeGoodsIdLists"];
            if (lists != null)
            {
                NonAvailbaleGoods.AddRange(lists.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
            }
        }

		public LikeTry(string uid, string pwd, string cookies, WaitCallback callBack = null)
		{
			this.UserName = uid;
			this.Password = pwd;
			this.Finished = callBack;
			this.Cookies = cookies;
	   
			this.Web = new WebHelper();
			this.Result = new Dictionary<TaskItem, bool>();

			foreach (int item in Enum.GetValues(typeof(TaskItem)))
			{
				this.Result.Add((TaskItem)item, false);
			}
		}

		/// <summary>
		/// 打卡
		/// </summary>
		public static readonly string DaKaUrl = "http://www.liketry.com/action/registration_ajax.php?action=daka";

		/// <summary>
		/// 社区
		/// </summary>
		public static readonly string BBSUrl = "http://www.liketry.com/header.php?menu=xssq ";

		/// <summary>
		/// 体验分享Url
		/// </summary>
		public static readonly string ShareUrl = "http://www.liketry.com/product_article_list.php"; /*liketry.com/share_list.php;*/

		/// <summary>
		/// 最新试用
		/// </summary>
		public static readonly string NewTryUrl = "http://www.liketry.com/try_index.php";


		/// <summary>
		/// 付费试用
		/// </summary>
		public static readonly string PayTryUrl = "http://www.liketry.com/likepay.php";

		/// <summary>
		/// 试用中心Url
		/// </summary>
		public static readonly string TryCenterUrl = "http://www.liketry.com/product_list.php";


		public static readonly string XiCongTianJiangUrl = "http://www.liketry.com/minisite/lottery/";

		/// <summary>
		/// 同楼
		/// </summary>
		public static readonly string TongLou = "http://www.liketry.com/api/tonglou/connect.php";

		/// <summary>
		/// 活动
		/// </summary>
		public static readonly string HouDong = "http://www.liketry.com/activity_list.php";


		public static readonly string Xingyundaren = "http://www.liketry.com/minisite/lot/ ";

		/// <summary>
		/// 用户信息
		/// </summary>
		public static readonly string UserInfoUrl = "http://www.liketry.com/user_default.php";

		public static readonly Regex MatchGoods = new Regex(@"<span class=""white14pxbold"">(?<xiyuan>\d*)喜元</span>.[^<]*<a href=""(?<url>.[^""]*)"".[^>]*class=""mt10px"" title=""(?<title>.[^"">]*)""><img src=""(?<isempty>.[^""]*)""/></a>");//, RegexOptions.Singleline | RegexOptions.Compiled);

		[Obsolete]
		public static readonly Regex MatchStatus = new Regex(@"<li class="" (?<item>.[^""]*) ""><a .[^>]*>.[^<]*</a><span></span></span></li>", RegexOptions.Compiled | RegexOptions.Singleline);

        public static readonly Regex MatchCanSendFeel = new Regex(@"'try_feeladd.php\?type=3&product_no=(?<goodid>\d*)'", RegexOptions.Compiled | RegexOptions.Singleline);

        public static readonly Regex MatchCanConfirm = new Regex(@"getGoods\((?<goodid>\d*),", RegexOptions.Compiled | RegexOptions.Singleline);

		public string LastSendEmailDate = string.Empty;

		#endregion

		#region Init
		public string Preview()
		{
			this.Logon();
			return Web.DoGet(UserInfoUrl);
		}

		/// <summary>
		/// 初始化系统
		/// </summary>
		public void KeepOnline()
		{
			try
			{
				if (!Initilzated)
				{
					var result = string.Empty;
					result = this.Logon();
					Web.DoGet(ShareUrl);
					CheckTaskStatus();
					GetUserInformation();
				}
			}
			catch
			{ }

		}
		private string Logon()
		{
			if (!string.IsNullOrEmpty(Cookies))
			{
				var cookiesLists = Cookies.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
				if (cookiesLists != null)
				{
					foreach (var cookie in cookiesLists)
					{
						Web.Cookie.SetCookies(new Uri("http://liketry.com"), cookie);
						Web.Cookie.SetCookies(new Uri("http://www.liketry.com"), cookie);
					}
				}

			}
			return string.Empty;
		}
		#endregion

		#region Like try Job
		public void Execute(object o)
		{
			do
			{
				try
				{
					this.KeepOnline();
					Thread.Sleep(5 * 1000);
					Web.DoGet(BBSUrl);
					Thread.Sleep(5 * 1000);
					Web.DoGet(ShareUrl);
					Thread.Sleep(5 * 1000);
					Web.DoGet(TryCenterUrl);
					Thread.Sleep(5 * 1000);
					CheckTaskStatus();
					var results = Result.Where(x => x.Value == false).Count();
					while(results > 0 )
					{
						this.ExecuteNavigateTask();
						this.ExecuteTimeTask();
						CheckTaskStatus();
						results = Result.Where(x => x.Value == false).Count();
					} 

					var currentDate = DateTime.Now.ToString("yyyy-MM-dd");
					if (LastSendEmailDate != currentDate)
					{
						////Send email only daily once.
						SmtpHelper.Send(OutputStatus(), this.UserName);
						LastSendEmailDate = currentDate;
					}

					try
					{
						EventLog.WriteEntry("Application", OutputStatus(), EventLogEntryType.Information);
					}
					catch (Exception exp)
					{ }

					Thread.Sleep(7 * 60 * 60 * 1000);
					if (this.Finished != null)
					{
						this.Finished(this);
					}
				}
				catch (Exception exp)
				{
				}
			} while (true);
		}

		private void ExecuteTimeTask()
		{
			do
			{
				if (Result[TaskItem._120min])
				{
					break;
				}
				else if (Result[TaskItem._60min])
				{
					ExecuteNormalTask(TaskItem._120min);
					Thread.Sleep(10 * 60 * 1000);
				}
				else if (Result[TaskItem._30min])
				{
					ExecuteNormalTask(TaskItem._60min);
					Thread.Sleep(10 * 60 * 1000);
				}
				else
				{
					ExecuteNormalTask(TaskItem._30min);
					Thread.Sleep(10 * 60 * 1000);
				}

				CheckTaskStatus();
			} while (!Result[TaskItem._120min]);
		}

		private void ExecuteNavigateTask()
		{
			var items = Enum.GetValues(typeof(TaskItem));
			foreach (var item in items)
			{
				switch ((TaskItem)item)
				{
					case TaskItem._120min:
					case TaskItem._30min:
					case TaskItem._60min:
						break;
					default:
						ExecuteNormalTask((TaskItem)item);
						break;
				}
			}
		}

		private void ExecuteNormalTask(TaskItem item)
		{
			///已经成功了
			if (Result[item])
			{
				return;
			}

			var ExecuteSuccess = false;
			int tryTimes = 0;
			do
			{
				var cando = this.CheckTask(item);
				if (cando)
				{
					////Submit task when task can done.
					ExecuteSuccess = this.ExecuteTask(item);
				}
				else
				{
					NavigatePage(item);
				}

				tryTimes++;
			}
			while (!ExecuteSuccess && tryTimes < MaxRetryTimes);

			Result[item] = ExecuteSuccess;
			if (!ExecuteSuccess)
			{
				Trace.Write(string.Format("Execute {0} Faile!", item.ToString()), "Error");
			}
			else
			{
				GetUserInformation();
			}
		}

		private bool CheckTask(TaskItem item)
		{
			var task = Web.DoGet(string.Format(GetTaskUrl, item.ToString()));
			if (true/*item != TaskItem._sc*/)
			{
				return task.Contains("check:1");
			}
			else {

				return true;
			}
		}

		private void NavigatePage(TaskItem item)
		{
			switch ((TaskItem)item)
			{
				case TaskItem._ty:
					Web.DoGet(TryCenterUrl);
					break;
				case TaskItem._share:
					Web.DoGet(ShareUrl);
					break;
				case TaskItem._daka:
					Web.DoGet(DaKaUrl);
					break;
				case TaskItem._bbs:
					Web.DoGet(BBSUrl);
					break;
				case TaskItem._newtry:
					Web.DoGet(NewTryUrl);
					break;
				case TaskItem._paytry:
					Web.DoGet(PayTryUrl);
					break;
				case TaskItem._lottery:
					Web.DoGet(XiCongTianJiangUrl);
					break;
				case TaskItem._tl:
					Web.DoGet(TongLou);
					break;
				case TaskItem._action:
					Web.DoGet(HouDong);
					break;
				case TaskItem._lucky:
					Web.DoGet(Xingyundaren);
					break;
			}
		}

		private bool ExecuteTask(TaskItem item)
		{
			var result = Web.DoGet(string.Format(ApplyTaskUrl,item.ToString()));
			Thread.Sleep(5 * 1000);
			return result.Contains("success:true");
		}

        private bool ExecuteWeekTask(string item)
        {
            var result = Web.DoGet(string.Format(ApplyWeekTaskUrl, item));
            Thread.Sleep(5 * 1000);
            return result.Contains("success:true");
        }

		private void GetUserInformation()
		{
			var content = Web.DoGet(UserInfoUrl);
			var userNamestart = content.IndexOf(@"yellow14pxbold"">");
			if (userNamestart != -1)
			{
				var userNameEnd = content.IndexOf("</span>", userNamestart);
				if (userNameEnd != -1)
				{
					this.UserName = content.Substring(userNamestart + @"yellow14pxbold"">".Length, userNameEnd - userNamestart - @"yellow14pxbold"">".Length);
                    if (this.UserName.Contains("<"))
                    {
                        var removeStart = this.UserName.IndexOf('<');
                        this.UserName = this.UserName.Remove(removeStart);
                    }
                }
			}

			////Faster than use regular expresstion.
			int start = content.IndexOf(@"<ul class=""web-info");
			if (start != -1)
			{
				var end = content.IndexOf("</ul>", start);
				if (end != -1)
				{
					content = content.Substring(start, end - start);
					var result = GetHtmlText(content);
					var s = result.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
					this.CurrentJiFen = Int32.Parse(s[8]);
					this.CurrentXiYuan = Int32.Parse(s[4]);
					Console.WriteLine(this.UserName + result);
				}
			}
		}

		private void CheckTaskStatus()
		{
			foreach (int item in Enum.GetValues(typeof(TaskItem)))
			{
				this.Result[(TaskItem)item] = false;
			}

			var result = Web.DoGet(CheckTaskOpen);
			var key = "task-nav-box-day";
			var start = result.IndexOf(key);
			if (start < 0) return;
			var end = result.IndexOf("</div>",start);
			var temp = result.Substring(start, end - start);

			start = 0;
			end = 0;
			key = "<ul>";
			start = temp.IndexOf(key);
			end = temp.IndexOf("</ul>");
			temp = temp.Substring(start, end - start);
			var items = Enum.GetNames(typeof(TaskItem));
			foreach (var item in items)
			{
				var task = (TaskItem)Enum.Parse(typeof(TaskItem), item, true);
				var li = string.Format(@"<li class="" d{0} "">",item);
				var i = temp.IndexOf(li);
				if (i != -1)
				{
					var j = temp.IndexOf("</li>", i);
					var lis = temp.Substring(i, j - i);

					Result[task] = lis.IndexOf("<span></span>") != -1;
				}
			}
		}

		private string OutputStatus()
		{
			StringBuilder sb = new StringBuilder();
			sb.AppendLine("< " + this.UserName + " > " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
			sb.AppendLine( "喜元" + CurrentXiYuan);
			foreach (var key in this.Result.Keys)
			{
				sb.AppendLine(string.Format("{0}  {1}", key, this.Result[key] ? "Yes" : "No"));
				sb.AppendLine();
			}

			Console.WriteLine(sb.ToString());

			return sb.ToString();
		}

		private string GetHtmlText(string html)
		{
			StringBuilder newText = new StringBuilder();
			bool inTag = false;
			foreach (var c in html)
			{
				if (c == '<')
				{
					inTag = true;
					continue;
				}

				if (c == '>')
				{
					inTag = false;
					if (newText.Length > 0)
					{
						if (newText[newText.Length - 1] != ',')
						{
							newText.Append(',');
						}
					}
					
					continue;
				}

				if (!inTag)
				{
					if (c != '\r' && c != '\n' && c != ' ')
					{
						newText.Append(c);
					}
				}
				
			}

			return newText.ToString();
		}

		private static string RemoveSymbol(string str)
		{
			StringBuilder sb = new StringBuilder();
			foreach (var c in str)
			{
				if (char.IsLetterOrDigit(c))
				{
					sb.Append(c);
				}
			}

			return sb.ToString();
		}
		#endregion

		/// <summary>
		/// Get Free try goods
		/// </summary>
		/// <returns></returns>
		private static List<GoodType> GetFreeTryGood()
		{
			WebHelper web = new WebHelper();
			var result = new List<GoodType>();
			var currentPage = 1;
			var response = string.Empty;//web.DoGet(string.Format("http://www.liketry.com/product_list.php?key=&lx_id=0&xy_desc=0&city=a&page_no={0}",currentPage));
			do
			{
				response = web.DoGet(string.Format("http://www.liketry.com/product_list.php?key=&lx_id=0&xy_desc=0&city=a&page_no={0}", currentPage));
				currentPage++;
				var matches = MatchGoods.Matches(response);

				foreach (Match item in matches)
				{
					if (item.Success)
					{
						if (item.Groups["isempty"].Value.Trim().ToLower().Equals(EmptyImageUrl.Trim().ToLower()))
						{
							continue;
						}
						else
						{
							var id = item.Groups["url"].Value.Trim().Remove(0, "/product_free_paytry.php?product_no=".Length - 1);
							var xiyuan = Int32.Parse(item.Groups["xiyuan"].Value.Trim());
							var title = item.Groups["title"].Value.Trim();
							result.Add(new GoodType { Id = id, XiYuan = xiyuan, Title = title });
						}
					}
				}
			}
			while (!response.Contains(EmptyImageUrl));

			return result;
		}

		#region Apply Goods

		public void RequestGood(object state)
		{
			LikeAccount account = state as LikeAccount;
			Queue<GoodType> queue = null;
			do
			{
				try
				{
					var haspendingGood = false;
					#region Store goods lists into queue

					////Sync control for multi thread write collection
					lock (LikeTry.AllGoods)
					{
						////Store list into queue.
						queue = new Queue<GoodType>(LikeTry.AllGoods);
					}

					#endregion

					////Default set to 25 hours.
					var pendingTimeSpan = new TimeSpan(25,0,0);
					while (queue != null && queue.Count > 0)
					{
						////Get goods form queue.
						var good = queue.Dequeue();
						////Skip apply goods if good id exists in non-available lists
						if (NonAvailbaleGoods.Contains(good.Id))
						{
							continue;
						}

						var result = ApplyStatusType.None;
						try
						{
							TimeSpan vipProtecttime = new TimeSpan();
							////  Time used for get apply goods start time.
							result = GetGoodStatus(good.Id, out vipProtecttime);
							switch (result)
							{
								//// Can Apply good now
								case ApplyStatusType.CanApply:
									ApplyGood(good);
									this.NonAvailbaleGoods.Add(good.Id);
									break;
								////When VIP/New protect time.
								case ApplyStatusType.VIPOnly:
									////if start time less than global sleep time.
									if ( pendingTimeSpan >  vipProtecttime)
									{
										////Set start time to new global time.
										pendingTimeSpan = vipProtecttime;
									}

									////If vip protect time less or equals than 5 mins, deep for apply goods 
									if (vipProtecttime.TotalMinutes <= 10)
									{
										ApplyGood(good);
										this.NonAvailbaleGoods.Add(good.Id);
									}
									else
									{
										////Set hasGood to true if has pending goods and waiting time large than 5 mins.
										haspendingGood = true;
									}

									break;
								default:
									this.NonAvailbaleGoods.Add(good.Id);
									break;
							}
						}
						catch(Exception exp)
						{
							Trace.Write(exp);
						}
					}

					////Have goods in vip protect time.
					if (haspendingGood)
					{
						var except = pendingTimeSpan - new TimeSpan(0, 10, 0);
						if (except.TotalMinutes > 0)
						{
							Trace.TraceInformation(DateTime.Now.ToString() + "-> " + account.Name+ " Sleep " + except.TotalMinutes + " Mins ");
							Thread.Sleep(except);
						}
					}
					//// No any goods exists for apply, sleep 'FrequTime', value define in app.config(30 Mins now) .
					else
					{
						var sleepTime = new TimeSpan(0, Convert.ToInt32(FrequTime), 0);
                        Trace.TraceInformation(DateTime.Now.ToString() + "-> " + account.Name + " Sleep " + sleepTime.TotalMinutes + " Mins ");
						Thread.Sleep(sleepTime);
					}

					Thread.Sleep(new TimeSpan(0,0,30));
				}
				catch(Exception exp)
				{
					Trace.Write(exp);
				}
			}
			while (true);
		}
		#endregion

        public static void FillGoodLists(object o)
        {
            while (true)
            {
                var goods = LikeTry.GetFreeTryGood();
                lock (LikeTry.AllGoods)
                {
                    LikeTry.AllGoods.Clear();
                    LikeTry.AllGoods.AddRange(goods);
                    Trace.TraceInformation("Get Goods list now: " + goods.Count + "  " + DateTime.Now.ToString());
                }
                if (o == null)
                {
                    Thread.Sleep(new TimeSpan(0, Convert.ToInt32(FrequTime), 0));
                }
                else
                {
                    break;
                }
            }

        }

		/// <summary>
		/// Get status by goods id 
		/// </summary>
		/// <param name="id">goods id</param>
		/// <param name="nextRun">waiting time</param>
		/// <returns></returns>
		private ApplyStatusType GetGoodStatus(string id, out TimeSpan nextRun)
		{
			nextRun = TimeSpan.MinValue;
			var result = ApplyStatusType.None;
			Web.DoGet(string.Format("http://www.liketry.com/product_free_paytry.php?product_no={0}", id));
			var step1Response = Web.DoGet(string.Format(ApplyGoodsStep1, id), ReturnType.String, false, null, true);
			if (step1Response.StartsWith("<script"))
			{
				var errorStart = step1Response.IndexOf("error=");
				if (errorStart != -1)
				{
					step1Response = step1Response.Substring(errorStart + "error=".Length, step1Response.Length - 11 - errorStart - "error=".Length);
				}

				var rawbyte = Convert.FromBase64String(step1Response);
				var message = UTF8Encoding.UTF8.GetString(rawbyte);

				if (message.IndexOf(AlreadyApplyErrorMessage) != -1)
				{
					result = ApplyStatusType.AlreadyApply;
				}
				else if (message.IndexOf(VIPErrorMessage) != -1)
				{
					result = ApplyStatusType.VIPOnly;
					try
					{
					  
						var start = message.IndexOf("还剩");
						if (start != -1)
						{
							var hoursEnd = message.IndexOf("小时");
							if (hoursEnd != -1)
							{
								var minend = message.IndexOf("分钟");
								if (minend != 1)
								{
									var hour = message.Substring(start+ 2, hoursEnd - start-2).Trim();
									var mins = message.Substring(hoursEnd + 2, minend - hoursEnd - 2).Trim();
									if (hour.StartsWith("0") && hour.Length >1)
									{
										hour = hour.Remove(0, 1);
									}
                                    
									if (mins.StartsWith("0") && mins.Length > 1)
									{
										mins = mins.Remove(0, 1);
									}

									Trace.TraceInformation(DateTime.Now.ToString() + message + " hour: " + hour + "  mins: " + mins);
									nextRun = new TimeSpan(Convert.ToInt32(hour), Convert.ToInt32(mins), 59);
								}
							}
						}
					}
					catch (Exception exp)
					{
						Trace.Write(exp);
						nextRun = new TimeSpan(0, 20, 0);
					}
				}
				else if (message.IndexOf(SchoolOnlyErrorMessage) != -1)
				{
					result = ApplyStatusType.SchoolOnly;
				}
				else if (message.IndexOf(XiYuanNotEnough) != -1)
				{
					result = ApplyStatusType.XiyuanNotEnough;
				}
				else
				{
					result = ApplyStatusType.OtherError;
				}
			}
			else
			{
				result = ApplyStatusType.CanApply;
			}

			return result;
		}

		/// <summary>
		/// Apply good
		/// </summary>
		/// <param name="good"></param>
		private void ApplyGood(GoodType good)
		{
			var result = ApplyStatusType.None;
			do
			{
				try
				{
					var step2 = Web.DoGet(string.Format("http://www.liketry.com/apply_delivery.php?radio=0&product_no={0}", good.Id), ReturnType.String, false, null, true);
					var step3 = string.Empty;
					var step4 = string.Empty;
					if (!step2.StartsWith("<script") && step2 != string.Empty)
					{
						step3 = Web.DoPost("http://www.liketry.com/apply_pay.php", string.Format("product_no={0}&radio=0", good.Id), false, null, true);
						if (step3 != string.Empty)
						{
							step4 = Web.DoPost("http://www.liketry.com/apply_success.php", string.Format("pay_type=0&product_no={0}&radio=0", good.Id), false, null, true);
							if (step4.Contains("恭喜您申领成功"))
							{
								result = ApplyStatusType.Successful;
							}
							else
							{
								TimeSpan time = new TimeSpan();
								result = GetGoodStatus(good.Id, out time);
								if (result != ApplyStatusType.VIPOnly)
								{
									result = ApplyStatusType.OtherError;
								}
							}
						}
					}
				}
				catch (Exception exp)
				{
					Trace.Write(exp);
				}
			} while (result == ApplyStatusType.VIPOnly);
		}

        /// <summary>
        /// Read account information from cookies file. 
        /// </summary>
        /// <exception cref="">thrwo exception when </exception>
        /// <returns></returns>
        public static List<LikeAccount> GetAccountList()
        {
            var accountObj = new List<LikeAccount>();
            try
            {
                var current = ReadAccountFromXml(LikeTry.AccountFileLocation);
                if (current != null)
                {
                    accountObj.AddRange(current);
                }
            }
            catch (Exception exp)
            {
                Trace.Fail(exp.ToString());
            }

            return accountObj;
        }

        private static List<LikeAccount> ReadAccountFromXml(string fileName)
        {
            DataContractSerializer contract = new DataContractSerializer(typeof(List<LikeAccount>));
            using (XmlReader writer = XmlReader.Create(fileName))
            {
                var current = contract.ReadObject(writer) as List<LikeAccount>;
                return current;
            }
        }

        private static void WriteAccountToXml(List<LikeAccount> accounts, string fileName)
        {
            DataContractSerializer contract = new DataContractSerializer(accounts.GetType());
            using (XmlWriter writer = new XmlTextWriter(fileName, Encoding.UTF8))
            {
                contract.WriteObject(writer, accounts);
            }
        }

        public static void AddAccount(LikeAccount account)
        {
            var current = GetAccountList();
            if (account != null)
            {
                current.Add(account);
                WriteAccountToXml(current, LikeTry.AccountFileLocation);
            }
        }
        public static void DeleteAccount(string guid)
        {
            var current = GetAccountList();
            var count = current.RemoveAll(x => x.Id == guid);
            if(count > 0)
            {
                WriteAccountToXml(current, LikeTry.AccountFileLocation);
            }
        }

        public void SendConfirmOrUserFeel(FeelOrConfirm type)
        {

            var lists = new List<string>();
            MatchCollection matchResult = null;
            
            var requestUrl = string.Empty;
            Regex g = null;
            WaitCallback callback = null;
            if (type == FeelOrConfirm.UserFeel)
            {
                requestUrl = "http://www.liketry.com/user_shenling.php?lb=dpj&page_no=1";
                g = MatchCanSendFeel;
                callback = SendUserFeelById;
            }
            else if (type == FeelOrConfirm.Confirm)
            {
                requestUrl = "http://www.liketry.com/user_shenling.php?lb=yfh&page_no=1";
                g = MatchCanConfirm;
                callback = SendReceiveGood;
                ////Weekly task
                //this.ExecuteWeekTask("applay");
            }
            else
            {
                return;
            }
            do
            {
                var content = Web.DoGet(requestUrl);
                matchResult = g.Matches(content);
                if (matchResult != null)
                {
                    foreach (Match item in matchResult)
                    {
                        if (item.Success)
                        {
                            lists.Add(item.Groups["goodid"].Value);
                        }
                    }
                }

                foreach (var item in lists)
                {
                    callback(item);
                    Thread.Sleep(new TimeSpan(0, 0, 15));
                }

                lists.RemoveRange(0, lists.Count);
            }
            while (matchResult != null && matchResult.Count > 0);
            this.GetUserInformation();
        }

        protected void SendUserFeelById(object goodId)
        {
            var feelContent = string.Format("article_no=&pic1=&pic2=&pic3=&extfield0=10&extfield1=10&extfield2=10&extfield3=10&extfield4=10&opt=addfeel&product_no={0}&type=3&order_no=0&content=%E7%9C%8B%E5%88%B0%E4%B8%9C%E8%A5%BF%E5%B0%B1%E7%94%B3%E8%AF%B7%E4%BA%86%EF%BC%8C%E8%BF%98%E6%B2%A1%E6%9C%89%E5%BC%80%E5%A7%8B%E7%94%A8%EF%BC%8C%E5%BA%94%E8%AF%A5%E4%B8%8D%E9%94%99%EF%BC%81",goodId);
            var referer = string.Format("http://www.liketry.com/try_feeladd.php?type=3&product_no={0}",goodId);
            Web.DoPost("http://www.liketry.com/try_feeladd.php", feelContent,false,null,false,referer);
        }

        protected void SendReceiveGood(object orderId)
        {
            var url = string.Format("http://www.liketry.com/action/order_ajax.php?action=ordergeted&orderid={0}",orderId);
            Web.DoGet(url);
        }
	}
}
